<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace Home\Controller;

use Think\Model;

/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
header('content-type:text/html;charset=utf8');

class PlanController extends HomeController
{
	/**
	 * 每日零点执行的任务计划
	 * 1：用户今日学习时长字段清零
	 * 2：7天自动确认收货
	 * 3：15天自动进行分账【包括上级用户的收益增加，调用封装方法：incShareUserProfit(支付用户id, 上级用户id, 分账后剩余金额)】
	 * 4：面授课是否截止报名（例：截止日期2021年4月1日；4月1日为报名的最后一天）
	 * */
	public function zeroPlan()
	{
		$time = time();

		//用户今日学习时长字段清零
		M('ucenter_member')->where('1 = 1')->setField('today_study_time', 0);

		//7天自动确认收货
		$auth_get_data = array(
			'status' => 3,
			'update_time' => $time
		);
		M('order')->where(array('type' => 4, 'is_pay' => 1, 'status' => 2, 'pay_time' => array('elt', $time - 7 * 24 * 3600)))->save($auth_get_data);

		//面授课是否截止报名（例：截止日期2021年4月1日；4月1日为报名的最后一天）
		$face_list = M('face_course')->where(array('status' => 1))->select();
		if($face_list){
			$face_ids = [];
		    foreach($face_list as &$v){
		        if(date('Y-m-d', $v['end_enlist_time']) <= date('Y-m-d',strtotime('-1 day'))){
		        	$face_ids[] = $v['id'];
		        }
		    }
		    if($face_ids){
			    $data = array(
				    'status' => 2,
				    'update_time' => $time
			    );
			    M('face_course')->where(array('id' => array('IN', $face_ids)))->save($data);
		    }
		}

		//15天自动进行分账
		$sharing_order_list = M('order_share_price')->where(array('status' => 1, 'share_time' => array('elt' => $time)))->select();
		if($sharing_order_list){
		    foreach($sharing_order_list as &$v){
		    	$pay_order_sn = getDbFieldValue('order', array('id' => $v['order_id']), 'pay_order_sn');
			    Vendor('pay.pay');
			    $query_data = array(
			    	'out_trade_no' => $pay_order_sn
			    );
			    $query_obj = new \pay($query_data);
			    $query_res = $query_obj->sharingQuery();

			    $receiver = json_decode($query_res['data']['receiver'], true);
				if($receiver){
					//分账人信息
					$pending_receivers = array();
				    foreach($receiver as &$val){
				        if($val['result'] == 'PENDING' || $val['result'] == 'FAIL'){
				        	$pending_receivers[] = array(
				        		'type' => $val['type'],
						        'account' => $val['account']
					        );
				        }
				    }

				    //分账解冻（开始分账）
					if($pending_receivers){
						$share_data = array(
							'out_trade_no' => $pay_order_sn,
							'receivers' => json_encode($pending_receivers)
						);
						$share_obj = new \pay($share_data);
						$share_res = $share_obj->sharing();

						if($share_res['result_code'] == 'SUCCESS'){
							shareSuccess($v['order_id']);
						}
					}
					sleep(1);
				}
		    }
		}
	}

	public function doPrice()
	{
		//15天自动进行分账
		$time = time();
		$sharing_order_list = M('order_share_price')->where(array('status' => 1))->select();
		if($sharing_order_list){
			foreach($sharing_order_list as &$v){
				$pay_order_sn = getDbFieldValue('order', array('id' => $v['order_id']), 'pay_order_sn');
				Vendor('pay.pay');
				$query_data = array(
					'out_trade_no' => $pay_order_sn
				);
				$query_obj = new \pay($query_data);
				$query_res = $query_obj->sharingQuery();

				$receiver = json_decode($query_res['data']['receiver'], true);
				if($receiver){
					//分账人信息
					$pending_receivers = array();
					foreach($receiver as &$val){
						if($val['result'] == 'PENDING' || $val['result'] == 'FAIL'){
							$pending_receivers[] = array(
								'type' => $val['type'],
								'account' => $val['account']
							);
						}
					}

					//分账解冻（开始分账）
					if($pending_receivers){
						$share_data = array(
							'out_trade_no' => $pay_order_sn,
							'receivers' => json_encode($pending_receivers)
						);
						$share_obj = new \pay($share_data);
						$share_res = $share_obj->sharing();

						if($share_res['result_code'] == 'SUCCESS'){
							shareSuccess($v['order_id']);
						}
					}
					sleep(1);
				}
			}
		}
	}

	/**
	 * 每分钟去检查拼团是否到时间
	 * */
	public function checkGroup()
	{
		$list = M('group_work')->where(array('status' => array('neq', 2)))->select();
		if($list){
		    foreach($list as &$v){

			    //将已到开始活动时间且未开始的团购活动开始
			    if($v['start_time'] > time() && $v['status'] == 0){
					M('group_work')->where(array('id' => $v['id']))->save(array('status' => 1, 'update_time' => time()));
				}

			    //将已到结束时间的团购活动修改为结束状态
			    if($v['end_time'] < time()){
				    M('group_work')->where(array('id' => $v['id']))->save(array('status' => 2, 'update_time' => time()));
			    	if($v['status'] == 1){
			    		//拼团列表
			    		$chief_group_join_list = M('group_join')->where(array('gid' => $v['id'], 'pid' => 0))->select();
			    		if($chief_group_join_list){
		                    foreach($chief_group_join_list as &$val){
								$son_count = M('group_join')->where(array('pid' => $val['id']))->count();
								if($son_count + 1 >= $v['people_number']){
									//拼团成功
									if($v['category'] == 1){
										//面授
									}else if($v['category'] == 2){
										//点播
										groupSuccess($v['id'], $val['id']);
									}else{
										//直播
									}
								}else{
									//拼团失败
								}
		                    }
					    }
				    }
			    }
		    }
		}
	}

}